package cn.td0f7.android.wangzhongcourse.utils.contentprovider;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;

public class UserContentProvider extends ContentProvider {

    private static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
    private DBOpenHelper dbHelper;

    //为了方便直接使用UriMatcher,这里addURI,下面再调用Matcher进行匹配
    static {
        matcher.addURI("cn.td0f7.app.android.providers.myprovider", "user", 1);
        matcher.addURI("cn.td0f7.app.android.providers.myprovider", "user2", 2);
        matcher.addURI("cn.td0f7.app.android.providers.myprovider", "user3", 3);
    }

    @Override
    public boolean onCreate() {
        dbHelper = new DBOpenHelper(this.getContext(), "user.db", null, 3);
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        return dbHelper.getReadableDatabase().query(uri.getPath().substring(1), null, null, null, null, null, null);
    }

    @Override
    public String getType(Uri uri) {
        return null;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        long rowId = dbHelper.getReadableDatabase().insert(uri.getPath().substring(1), null, values);
        if (rowId > 0) {
            //在前面已有的Uri后面追加ID
            Uri nameUri = ContentUris.withAppendedId(uri, rowId);
            //通知数据已经发生改变
            getContext().getContentResolver().notifyChange(nameUri, null);
            return nameUri;
        }
        return null;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        return dbHelper.getReadableDatabase().delete(uri.getPath().substring(1), selection, selectionArgs);
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        return dbHelper.getReadableDatabase().update(uri.getPath().substring(1), values, selection, selectionArgs);
    }

}